from django.shortcuts import render
from django.views import View
from django import http
from django.core.paginator import Paginator, EmptyPage

from haystack.views import SearchView

from apps.contents.models import GoodsCategory
from apps.goods.models import SKU
from apps.goods.utils import get_breadcrumb

# Create your views here.


class ListView(View):
    """
    商品列表页
    GET：/list/(?P<category_id>\d+)/skus/
    """
    def get(self, request, category_id):
        page_num = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')

        try:
            category = GoodsCategory.objects.get(id=category_id)
        except category.DoesNotExist:
            return http.JsonResponse({'code': 400, 'errmsg': 'category_id不存在'})

        # 查询指定分类下未被下架的商品信息（sku信息）并按照前段要求排序排序
        skus = SKU.objects.filter(category=category, is_launched=True).order_by(ordering)
        # 分页查询
        # 创建分页器对象：分页器对象 = Paginator(要分页的查询集, 每页记录个数)
        paginator = Paginator(skus, page_size)

        try:
            # 获取指定页中的模型数据：paginator.page(页码)
            page_skus = paginator.page(page_num)
        except EmptyPage:
            return http.JsonResponse({'code': 400, 'errmsg': '页码错误'})

        # 获取面包屑导航
        breadcrumb = get_breadcrumb(category)

        list = []
        for sku in page_skus:
            list.append({
                "id": sku.id,
                "default_image_url": sku.default_image.url,
                "name": sku.name,
                "price": sku.price
            })

        return http.JsonResponse({
            "code": 0,
            "errmsg": "ok",
            "breadcrumb": breadcrumb,
            "list": list,
            "count": paginator.num_pages
        })


class HotGoodsView(View):
    def get(self, request, category_id):
        try:
            skus = SKU.objects.filter(category_id=category_id).order_by('-sales')[:2]
        except Exception as e:
            return http.JsonResponse({"code": 400, "errmsg": "获取商品出错"})
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                "id": sku.id,
                "default_image_url": sku.default_image.url,
                "name": sku.name,
                "price": sku.price
            })
        return http.JsonResponse({
            "code": 0,
            "errmsg": "ok",
            "hot_skus": hot_skus
        })


class MySearchView(SearchView):
    """自定义商品搜索视图
    目的：为了重写create_response(),并返回检索后的JSON数据
    GET /search/
    """
    def create_response(self):
        # 获取检索到的数据
        context = self.get_context()
        # 获取检索到的模型数据
        results = context["page"].object_list
        # 便利results,取出检索到的SKU，转成字典
        data_list = []
        for result in results:
            data_list.append({
                'id': result.object.id,
                'name': result.object.name,
                'price': result.object.price,
                'default_image_url': result.object.default_image.url,
                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count
            })
        # 讲检索到的数据转换为json格式的数据
        return http.JsonResponse(data_list, safe=False)
